import 'package:diary/router/routes.dart';
import 'package:diary/ui/index/index.dart';
import 'package:diary/util/shared_pref_util.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

final router = FluroRouter();

void main() {
  // 配置路由
  Routes.configureRoutes(router);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
        localizationsDelegates: const [
          GlobalWidgetsLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        supportedLocales: const [
          Locale('zh', 'CH')
        ],
        locale: const Locale('zh'),
        onGenerateRoute: router.generator,
        home: const Diary());
  }
}

class Diary extends StatefulWidget {
  const Diary({Key? key}) : super(key: key);

  @override
  State<Diary> createState() => _DiaryState();
}

class _DiaryState extends State<Diary> {
  String? username;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 未进行资料配置，跳转到相应页面进行
      _jumpToAppConfig();
    });
  }

  _jumpToAppConfig() async {
    username = await SharedPrefUtil.instance.readUsername();
    if (username == null || username == "") {
      router.navigateTo(context, Routes.appConfigurationPage, clearStack: true);
    } else {
      showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: const Text("欢迎"),
            content: Text(username!),
            actions: [
              CupertinoDialogAction(
                child: const Text("确定"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return const IndexPage();
  }
}
